<?php

namespace app\api\controller;

use app\api\annotation\LoginRequired;
use app\api\basic\BaseController;
use plugin\saiadmin\utils\Arr;
use support\Request;
use app\activity\logic\activityLogic;
use app\project\logic\projectLogic;
use app\reservation\logic\reservationLogic;
use app\signup\logic\signupLogic;
use app\space\logic\spaceLogic;
use app\api\logic\CollectionLogic;
use plugin\saiadmin\app\logic\system\SystemConfigLogic;
class SpaceController extends BaseController {
     protected $userInfo;

    /**
     * 当前登陆管理员ID
     */
    protected $userId;

    /**
     * 当前登陆管理员账号
     */
    protected $userName;
    public function __construct()
    {   
        parent::__construct();
        $this->userId=request()->userId;
        $this->userName=request()->userName;
        $this->userInfo=request()->userInfo;
    }
    //厂房
    #[LoginRequired(required: false)]
    public function lists(Request $request){
        $param = $request->more([
            ['lang_code','zh'],
            ['limit',10],
            ['page',1],
            ['space_class',''],
            ['space_title','']
           
        ]);
        $space=new spaceLogic();
        if(!empty($param['space_title'])){
            $arr=[];
        }else{
            $arr =[
                'space_class'=>$param['space_class'],
            ];
        }
        $query=$space->search($arr);

        if($param['space_title']){
            $query->where('space_title', 'like', "%{$param['space_title']}%");

        }
        $spaceData=$query
       ->field('space_id,space_title,space_image,rent_nature,rent_price,building_area,address,project_id,space_images,vr_image,create_time')
        ->whereNull('delete_time')

        ->order('sort_order desc')
            ->order('create_time desc')
        ->paginate($param['limit']);
        return $this->success(['data'=>$spaceData->items(),'total'=>$spaceData->total()]);
    }
    //厂房详情
    #[LoginRequired(required: false)]
    public function detail(Request $request){
        $param = $request->more([
            ['lang_code','zh'],
            ['space_id',''],
        ]);
        $space=new  spaceLogic();
        $project=new projectLogic();
         $collectionLogic=new CollectionLogic();
        $spaceData=$space->search(['space_id'=>$param['space_id']])
        ->field('space_id,space_title,space_image,rent_nature,project_id,
        rent_price,building_area,day_price,address,create_time,space_detail,rent_area,space_images,vr_image,vr_link,main_use,longitude,latitude')
        ->whereNull('delete_time')
        ->order('sort_order desc')
        ->order('create_time desc')
        ->find();

        if(empty($spaceData['longitude']) || empty($spaceData['latitude'])){
            // 替换为你的API密钥
            $logic = new SystemConfigLogic();
            $wechatConfig = $logic->getGroup('map_config');
            $apiKey=Arr::getConfigValue($wechatConfig,'mapKey');
         //   $apiKey = "QFRBZ-KT3W7-ZQGXD-PGUBE-TIIPF-7CB7L";

            // 要查询的地址
            $address =$spaceData['address'];

            // 调用函数获取经纬度
            $coordinates = getLocation($address, $apiKey);

            $result = json_decode($coordinates, true);
            // 提取经纬度
            if(isset($result['status']) && $result['status'] == 0) {

                  $spaceData['longitude']=$result['result']['location']['lng'];
                  $spaceData['latitude'] =$result['result']['location']['lat'];

                $space->where('space_id',$spaceData['space_id'])->update(['longitude'=>$spaceData['longitude'],'latitude'=>$spaceData['latitude']]);
            }
        }

        if($spaceData){
            $data['space']=$spaceData->toArray();
           
            $projectData=$project->search(['project_id'=>$spaceData->project_id])->find();
            if(!$projectData) return $this->fail('项目不存在');
            $data['project']=$projectData->toArray();
             //获取是否收藏
            $data['is_collection']=0;
            $collectionRes=$collectionLogic->where(['type'=>4,'collection_id'=>$param['space_id'],'user_id'=>$this->userId])->findOrEmpty();
        
            if(!$collectionRes->isEmpty())$data['is_collection']=1;
            return $this->success($data);
        }
        return $this->fail('数据不存在');
    }
    //预约
   
    public function saveReservation(Request $request){
        $param = $request->more([
            ['project_id',''],
            ['lang_code','zh'],
            ['space_id',''],
            ['reservation_time_slot',''],
            ['id_number',''],
            ['phone_number',''],
             ['reservation_person',''],
            ['reservation_number',''],
            ['reservation_time','']
        ]);
         $validate = $this->validate->rule([
        'project_id'    => 'require|number',
        'space_id'=>'require|number',
      
        'reservation_time_slot'    => 'require|max:50',
//        'id_number'            => 'require',
        'phone_number'   => 'require|regex:/^1[3-9]\d{9}$/',
        'reservation_person'   => 'require|max:100',
        'reservation_number'   => 'require|max:100',
        'reservation_time'   => 'require|max:100',
    ])->message([
        'project_id.require' => '项目ID不能为空',
        'space_id.require' => '厂房ID不能为空',
      
        'reservation_time_slot.require'  => '预约时间段不能为空',
//        'id_number.require'=>'身份证号码不能为空',
        'phone_number.require'=>'手机号码不能为空',
        'phone_number.regex'=>'手机号码格式错误',
        'reservation_person.require'=>'预约人不能为空',
        'reservation_number.require'=>'预约人数不能为空',
        'reservation_time.require'=>'预约时间不能为空',
    ]);

    if (!$validate->check($param)) {
        return $this->fail($validate->getError());
    }
     if($param['reservation_time'] < date('Y-m-d')) return $this->fail('预约时间不能小于当前时间');
        $param['user_id']=$this->userId;
        $reservation=new reservationLogic();
        $project=new projectLogic();
        $res=$reservation->search(['user_id'=>$this->userId,
        'space_id'=>$param['space_id'],
        'reservation_time_slot'=>$param['reservation_time_slot'],
        'reservation_time'=>$param['reservation_time']])->find();
        if($res) return $this->fail('请勿重复预约');
         $res_project=$project->where('project_id',$param['project_id'])->findOrEmpty();
        if($res_project->isEmpty()) return $this->fail('项目不存在');
        $param['project_title'] =$res_project['project_title'];

        $reservationData=$reservation->create($param);
        if($reservationData){
            return $this->success('预约成功');
        }
        return $this->fail('预约失败');
    }
  
   
   
}